<?php

namespace App\Helper;

use Illuminate\Support\Facades\Cache;

/**
 * 友盟sdk
 */
class UmengSDK
{
    protected $config=null;
    protected $host="https://verify5.market.alicloudapi.com";
    protected $path = "/api/v1/mobile/info";
    protected $appKey = "204075614"; //阿里云市场购买应用的appKey
    protected $appSecret = "QNkH0qKrGpcpg7Hkv7AIyadCA18N1Dle"; //阿里云市场购买应用的appSecret
    protected $um_appkey = "629f04f205844627b5a4375e"; //友盟的appkey
    protected $post_data=[];
    protected $header=[];
    protected $method = "POST";
    public function __construct($mobile_token="")
    {
        $accept = "application/json";
        $content_type = "application/json; charset=UTF-8";

        $this->header["Accept"] = $accept;
        $this->header["Content-Type"] = $content_type;
        $this->header["X-Ca-Version"] = "1";
        $this->header["X-Ca-Signature-Headers"] = "X-Ca-Key,X-Ca-Nonce,X-Ca-Stage,X-Ca-Timestamp,X-Ca-Version";
        $this->header["X-Ca-Stage"] = "RELEASE";
        $this->header["X-Ca-Key"] = $this->appKey; //请求的阿里云AppKey
        $this->header["X-Ca-Timestamp"] = strval(time() * 1000);
        mt_srand((double) microtime() * 10000);
        $uuid = strtoupper(md5(uniqid(rand(), true)));
        $this->header["X-Ca-Nonce"]=strval($uuid);
        //Headers
        $headers = "X-Ca-Key:" . $this->header["X-Ca-Key"] . "\n";
        $headers .= "X-Ca-Nonce:" . $this->header["X-Ca-Nonce"] . "\n";
        $headers .= "X-Ca-Stage:" . $this->header["X-Ca-Stage"] . "\n";
        $headers .= "X-Ca-Timestamp:" . $this->header["X-Ca-Timestamp"] . "\n";
        $headers .= "X-Ca-Version:" . $this->header["X-Ca-Version"] . "\n";
        //Url
        $url = $this->path . "?appkey=" . $this->um_appkey; //appkey为用户在友盟注册的应用分配的appKey,token和phoneNumber是app传过来的值
        //sign
        $str_sign = $this->method . "\n";
        $str_sign .= $accept . "\n";
        $str_sign .= "\n";
        $str_sign .= $content_type . "\n";
        $str_sign .= "\n";
        $str_sign .= $headers;
        $str_sign .= $url;
        $sign = base64_encode(hash_hmac('sha256', $str_sign, $this->appSecret, true)); //secret为APP的密钥
        $this->header['X-Ca-Signature'] = $sign;

        $this->post_data['token'] = $mobile_token;
    }

    /**
     * 手机认证
     * @return bool|string
     */
    public function mobile(){
        $url = $this->host . $this->path . "?appkey=" . $this->um_appkey; //appkey为用户在友盟注册的应用分配的appKey
        $headerArray = array();
        foreach ($this->header as $k => $v) {
            array_push($headerArray, $k . ":" . $v);
        }
        return json_decode(request_post($url,$this->post_data,$headerArray,$this->method),true);
    }


}
